package dao.mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

public class MySqlImpl {
	private static final String dbUrl = "jdbc:mysql://localhost:3306/leaveapplicationdb";
	private static final String dbUserName = "root";
	private static final String dbPassword = "password";

	private Statement statement = null;
	private Connection conn = null;

	private void createStatement(){
		try {
			try {
				Class.forName("com.mysql.jdbc.Driver");
			} catch (ClassNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			conn = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
			statement = conn.createStatement();
		} catch (SQLException e) {
			String error = "Error selecting users. Nested Exception is: " + e;
			Logger.getLogger(getClass().getName()).log(Level.SEVERE, error);
		}
	}

	public int execute(String sql) throws SQLException {
		this.createStatement();
		int result;
		Logger.getLogger(getClass().getName()).log(Level.INFO,
				"Executing : " + sql);
		result = statement.executeUpdate(sql);
		
		return result;
	}

	public ResultSet get(String sql) throws SQLException {
		this.createStatement();
		ResultSet result;
		Logger.getLogger(getClass().getName()).log(Level.INFO,
				"Retrieving : " + sql);
		result = statement.executeQuery(sql);
		
		return result;
	}

	public void close() throws SQLException {
		statement.close();
		conn.close();
	}

	public void commit() throws SQLException {
		conn.commit();
	}

	public void rollBack() throws SQLException {
		conn.rollback();
	}
}
